//活动接口
const express = require('express')
const router = express.Router()
const { activity } = require('../dao/index.js')
const { addPart}=require('../serve/bonus.js')
router.get('/data', function (req, res, next) {
    activity.find({}, function (err, data) {
        res.json(data)
    })
})

router.get("/list", function (req, res, next) {
    activity.findById(req.query.id, function (err, data) {
        res.json(data)
    })
})

//活动报名接口
router.get('/apply', function (req, res, next) {
    activity.findByIdAndUpdate(req.query.id, {
        $push: {
            "people": [req.query.data]
        }
    }, function (err, data) {
        if (err) {
            res.json({
                status: false,
                err: '报名失败'
            })
        } else {
            res.json({
                status: true,
                err: '报名成功',
                data
            })
        }

    })
})

//活动签到接口
router.get('/signin', function (req, res, next) {
    req.query.id
    activity.findById(req.query.id, {
        people: 1,
        password: 1
    }, function (err, data) {
        if (req.query.paw == data.password) {
            var info = new Map(data.people)
            info.set(req.query.useId, true)
            var a = Array.from(info)
            console.log(a)
            activity.findByIdAndUpdate(req.query.id, { people: a }, function (err,data) {
                if (err) {
                    res.json({
                        status: false,
                        err:'签到出错，稍后再试'
                    })
                } else {
                    addPart(req.query.useId, data.grade)
                    res.json({
                        status: true,
                        lay:'签到成功',
                        data
                    })
                }
            })
        } else {
            res.json({
                status: false,
                err: '签到密码错误'
            })
        }
    })
})

//添加活动
router.post('/add', function (req,res,next) {
    activity.create(req.body.info, function (err, data) {
        if (err) {
            res.json({
                status:false,
                err:'添加失败'
            })
        } else {
            res.json({
                status: true,
                lay:'添加成功'
            })
        }
    })
})
module.exports = router
